<template>
  <a-modal
    :title='title'
    :width='1100'
    :visible='visible'
    :centered='true'
    :confirmLoading='confirmLoading'
    :maskClosable='false'
    @ok='handleSubmit'
    @cancel='handleCancel'
  >
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-form-item :colon='false' label=' ' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <div style='text-align: right'><a @click='showPresalesModel'>从售前客户中选择</a></div>
        </a-form-item>
        <a-form-item label='业务类型' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-radio-group
            v-decorator="['customer_identity', {initialValue:0, rules: [{ required: true }]}]"
            button-style='solid'
          >
            <a-radio-button :value='0'>
              个人
            </a-radio-button>
            <a-radio-button :value='1'>
              公司
            </a-radio-button>
          </a-radio-group>
        </a-form-item>
        <template v-if='!form.getFieldValue(&quot;customer_identity&quot;)'>
          <a-form-item label='客户姓名' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input
              placeholder='请输入客户姓名'
              v-decorator="['full_name', { rules: [{ required: true, message: '请输入客户姓名' }] }]"
            />
          </a-form-item>
          <a-form-item label='身份证号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input
              placeholder='请输入身份证号'
              v-decorator="['idnumber', { rules: [{ required: false, message: '请输入身份证号' }] }]"
            />
          </a-form-item>
        </template>
        <template v-if='form.getFieldValue(&quot;customer_identity&quot;)==1'>
          <a-form-item label='公司名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input
              placeholder='请输入公司名称'
              v-decorator="['corporate_name', { rules: [{ required: true, message: '请输入公司名称' }] }]"
            />
          </a-form-item>

          <a-form-item label='授权签约人' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-input
              placeholder='请输入授权签约人'
              v-decorator="['signatory', { rules: [{ required: true, message: '请输入授权签约人' }] }]"
            />
          </a-form-item>
        </template>
        <a-form-item label='手机号码' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <a-input
            placeholder='请输入手机号码'
            v-decorator="['mobile', { rules: [{ required: true, message: '请输入手机号码' }] }]"
          />
        </a-form-item>
        <a-form-item label='公司类型' :labelCol='labelCol' :wrapperCol='HwrapperCol'>
          <a-radio-group
            v-decorator="['corporate_type', {initialValue:0, rules: [{ required: true }]}]"
            button-style='solid'
            @change='rendFwnr'
          >
            <a-radio-button :value='0'>
              个体户
            </a-radio-button>
            <a-radio-button :value='1'>
              小规模纳税人
            </a-radio-button>
            <a-radio-button :value='2'>
              一般纳税人
            </a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item label='客户所在区域' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <SelectRegion
            v-decorator="['region', { rules: [{ required: true, message: '请选择客户所在区域' }] }]"
          />
        </a-form-item>
        <a-form-item label='客户来源' :labelCol='labelCol' :wrapperCol='wrapperCol'>
          <SelectPresalesSource
            width='100%'
            placeholder='请选择客户来源'
            v-decorator="['pcs_id', { rules: [{ required: true, message: '请选择客户来源' }] }]"
          />
        </a-form-item>
        <template v-if='mode===&quot;add&quot;'>
          <a-divider orientation='left'>
            服务内容
          </a-divider>
          <div style='margin-bottom: 20px'>
            <a-button style='margin-bottom: 10px' @click='addFwnrList'>增加一项</a-button>
            <table border='1' style='border-color: #e8e8e8;width: 100%;text-align: center'>
              <tr style='font-weight: 600'>
                <td>服务名称</td>
                <td>标准价格</td>
                <td>成交价格</td>
                <td>服务周期（月）</td>
                <td>本次收款</td>
                <td>剩余尾款</td>
                <td>操作</td>
              </tr>
              <tr v-for='(item,index) in fwnr'>
                <td style='min-width: 280px'>
                  <a-select
                    allowClear
                    show-search
                    :filter-option='filterOption'
                    placeholder='请选择服务内容'
                    v-model='item.service_id'
                    @change='setTrData($event,index)'
                  >
                    <a-select-option v-for='item in service_list' :value='item.service_id'>
                      {{ item.service_name }}
                    </a-select-option>
                  </a-select>
                </td>
                <td style='min-width: 80px'><span style='color: red'>￥</span>{{ item.standard_price || '-' }}</td>
                <td>
                  <span style='color: red'>￥</span>
                  <a-input-number
                    :min='0'
                    style='width: 100px'
                    v-model='item.deal_price'
                    @change='(e)=>{
                      item.collection_price=e
                      item.balance_price=e-item.collection_price
                    }'
                  />
                  元
                </td>
                <td>
                  <a-input-number :min='0' style='width: 100px' v-model='item.month' />
                  月
                </td>
                <td>
                  <span style='color: red'>￥</span>
                  <a-input-number
                    :min='0'
                    style='width: 100px'
                    v-model='item.collection_price'
                    @change='(e)=>{
                      if(e>item.deal_price){
                        item.collection_price=item.deal_price
                      }
                      item.balance_price=item.deal_price-item.collection_price
                    }' />
                  元
                </td>
                <td>
                  <span style='color: red'>￥</span>{{ item.balance_price === '' ? '-' : item.balance_price }} 元
                </td>
                <td>
                  <a style='color: red' @click='delFwnrList(index)'>删除</a>
                </td>
              </tr>
            </table>
          </div>
          <a-form-item label='服务说明' :labelCol='labelCol' :wrapperCol='wrapperCol'>
            <a-textarea
              :maxLength='500'
              v-decorator="['service_desc', { rules: [{ required: true,message: '请输入服务说明' }] }]"
              placeholder='请输入服务说明'
              :auto-size='{ minRows: 5, maxRows: 8 }'
            />
          </a-form-item>
          <a-form-item label='付款方式' :labelCol='labelCol' :wrapperCol='HwrapperCol'>
            <a-radio-group
              button-style='solid'
              v-decorator="['pay_type', {initialValue:1, rules: [{ required: true }]}]"
            >
              <a-radio-button :value='1'>
                转账汇款
              </a-radio-button>
              <a-radio-button :value='2'>
                现金
              </a-radio-button>
            </a-radio-group>
          </a-form-item>
        </template>
      </a-form>
    </a-spin>
    <presales-customer-model ref='PresalesCustomerModel' @handleSuccess='setFormData' />
  </a-modal>
</template>

<script>
import _ from 'lodash'
import * as serviceApi from '@/api/service'
import * as Api from '@/api/customer'
import { PresalesCustomerModel, SelectPresalesSource, SelectRegion } from '@/components'

export default {
  components: {
    SelectPresalesSource,
    SelectRegion,
    PresalesCustomerModel
  },
  data() {
    return {
      // 对话框标题
      title: '',
      // 标签布局属性
      labelCol: {
        span: 7
      },
      // 输入框布局属性
      wrapperCol: {
        span: 13
      },
      HwrapperCol: {
        span: 17
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 当前记录
      record: {},
      // 当前模式
      mode: '',
      fwnr: [{
        service_id: '',
        standard_price: '',
        deal_price: '',
        month: '',
        collection_price: '',
        balance_price: ''
      }],
      service_list: []
    }
  },
  methods: {
    setFormData(item) {
      this.form.setFieldsValue({
        full_name: item.full_name,
        idnumber: item.idnumber,
        mobile: item.mobile,
        corporate_name: item.corporate_name,
        signatory: item.signatory,
        pcs_id: item.pcs_id,
      })
    },
    showPresalesModel() {
      this.$refs.PresalesCustomerModel.open()
    },
    // 多选框搜索配置
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // 显示对话框
    add() {
      this.mode = 'add'
      this.title = '录入成交客户'
      this.visible = true
      this.getAllService()
    },
    edit(record) {
      this.mode = 'edit'
      this.title = '编辑成交客户'
      this.visible = true
      this.record = record
      this.getAllService()
      this.setFieldsValue()
    },

    setTrData(e, index) {
      const corporateType = this.form.getFieldValue('corporate_type')
      const corporateTypes = [
        'gth',
        'xgmnsr',
        'ybnsr'
      ]
      const item = this.service_list.find(item => item.service_id === e)
      this.fwnr[index].standard_price = item[corporateTypes[corporateType] + '_standard_price']
      this.fwnr[index].deal_price = item[corporateTypes[corporateType] + '_standard_price']
      this.fwnr[index].collection_price = item[corporateTypes[corporateType] + '_standard_price']
      this.fwnr[index].balance_price = 0
    },
    rendFwnr({ target: { value } }) {
      const corporateType = value
      const corporateTypes = [
        'gth',
        'xgmnsr',
        'ybnsr'
      ]
      this.fwnr.forEach(item => {
        if (item.service_id) {
          const serviceItem = this.service_list.find(item2 => item2.service_id === item.service_id)
          item.standard_price = serviceItem[corporateTypes[corporateType] + '_standard_price']
          item.deal_price = serviceItem[corporateTypes[corporateType] + '_standard_price']
          item.collection_price = serviceItem[corporateTypes[corporateType] + '_standard_price']
          item.balance_price = 0
        }
      })
    },
    hasEmptyValue(arr) {
      return arr.some(obj => Object.values(obj).some(value => value === ''))
    },
    // 获取所有服务内容
    async getAllService() {
      const { data: { list } } = await serviceApi.all()
      this.service_list = list
    },
    // 增加一项服务内容
    addFwnrList() {
      this.fwnr.push({
        service_id: '',
        standard_price: '',
        deal_price: '',
        month: '',
        collection_price: '',
        balance_price: ''
      })
    },
    delFwnrList(index) {
      this.fwnr.splice(index, 1)
    },
    // 设置默认值
    setFieldsValue() {
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        const data = _.pick(this.record, Object.keys(this.record))
        setFieldsValue(data)
        this.$nextTick(() => {
          setFieldsValue(data)
        })
      })
    },

    // 确认按钮
    handleSubmit(e) {
      e.preventDefault()
      const { form: { validateFields } } = this
      // 表单验证
      validateFields((errors, values) => {
        // 提交到后端api
        !errors && this.onFormSubmit(values)
      })
    },

    // 关闭对话框事件
    handleCancel() {
      this.visible = false
      this.form.resetFields()
    },

    // 提交到后端api
    onFormSubmit(values) {
      var api
      if (this.mode === 'add') {
        if (this.hasEmptyValue(this.fwnr)) {
          this.$message.error('请完善服务内容！')
          return false
        }
        values.serviceTable = this.fwnr
        api = Api.add({ form: values })
      } else {
        api = Api.edit({ apiId: this.record['customer_id'], form: values })
      }
      this.confirmLoading = true

      api.then(result => {
        // 显示成功
        this.$message.success(result.message, 1.5)
        // 关闭对话框
        this.handleCancel()
        // 通知父端组件提交完成了
        this.$emit('handleSubmit', values)
      })
        .finally(result => {
          this.confirmLoading = false
        })
    }

  }
}
</script>
